import java.util.ArrayList;
import java.util.List;

public class BM23 {


      public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
          this.val = val;
        }
      }

    public int[] preorderTraversal (TreeNode root) {
        // write code here
        if (root == null) return new int[0];
        List<Integer> res = new ArrayList<>();
        int count = 0;
        preorderTraversalHelper(root,count,res);
        int[] arr = new int[res.size()];
        for(int i = 0 ; i<res.size();i++){
            arr[i] = res.get(i);
        }
        return arr;
    }

    private void preorderTraversalHelper(TreeNode root,int count,List res){
        res.add(root.val);
        if(root.left != null){
            preorderTraversalHelper(root.left,count + 1,res);
        }
        if(root.right != null){
            preorderTraversalHelper(root.right,count + 1,res);
        }
    }
}
